<template>
  <Dialog v-model="visible" title="登记面试信息" width="520px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="90px"
      v-loading="loading"
    >
      <el-form-item label="应聘人员" prop="name">
        <el-input v-model="formData.name" placeholder="请输入求职人员" />
      </el-form-item>
      <el-form-item label="应聘岗位" prop="post">
        <el-cascader
          v-model="formData.post"
          :options="postOptions"
          :props="postProps"
          :show-all-levels="false"
          clearable
          filterable
          class="!w-100%"
          placeholder="请选择应聘岗位"
        />
      </el-form-item>
      <el-form-item label="邀约人" prop="inviter">
        <CascaderUser v-model="formData.inviter" placeholder="请选择邀约人" />
      </el-form-item>
      <el-form-item label="面试时间" prop="interviewTime">
        <el-date-picker
          v-model="formData.interviewTime"
          type="datetime"
          value-format="x"
          placeholder="选择日期时间"
          class="!w-100%"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="urgentPhone">
        <el-input v-model="formData.urgentPhone" placeholder="请输入手机" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false" :disabled="loading">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import CascaderUser from '@/components/CascaderUser/CascaderUser.vue'
import { RecruitPostApi, type RecruitPost } from '@/api/business/hr/recruit/post'
import { handleTree } from '@/utils/tree'
import { RecruitInterviewApi, type RecruitInterview } from '@/api/business/hr/recruit/interview'
import { useUserStore } from '@/store/modules/user'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from '@/hooks/web/useI18n'

interface RecruitPostCascaderNode extends RecruitPost {
  value: string
  label: string
  isLeaf?: boolean
  children?: RecruitPostCascaderNode[]
}

const visible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()
const userStore = useUserStore()
const message = useMessage()
const { t } = useI18n()

// 添加表单类型和ID变量
const formType = ref<'create' | 'update'>('create')
const currentId = ref<number | undefined>(undefined)

const postOptions = ref<RecruitPostCascaderNode[]>([])
const postProps = {
  value: 'post',
  label: 'post',
  emitPath: false,
  checkStrictly: true,
  leaf: 'isLeaf'
}

const formData = reactive({
  name: '',
  post: undefined as string | undefined,
  inviter: undefined as string | undefined,
  interviewTime: '',
  urgentPhone: '',
  remark: ''
})

const formRules: FormRules = {
  name: [{ required: true, message: '请输入求职人员', trigger: 'blur' }],
  post: [{ required: true, message: '请选择应聘岗位', trigger: 'change' }],
  inviter: [{ required: true, message: '请选择邀约人', trigger: 'change' }],
  interviewTime: [{ required: true, message: '请选择面试时间', trigger: 'change' }],
  urgentPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
}

const resetForm = () => {
  formData.name = ''
  formData.post = undefined
  const currentUserId = userStore.getUser.id
  formData.inviter = currentUserId ? String(currentUserId) : undefined
  formData.interviewTime = ''
  formData.urgentPhone = ''
  formData.remark = ''
  formRef.value?.clearValidate()
}

const loadPostOptions = async () => {
  if (postOptions.value.length) return
  try {
    const data = await RecruitPostApi.getRecruitPostList({})
    const tree = handleTree(data || [], 'id', 'parentId') as RecruitPostCascaderNode[]
    const markLeaf = (nodes: RecruitPostCascaderNode[]) => {
      nodes.forEach((node) => {
        node.value = node.post || `${node.id}`
        node.label = node.post || node.dept || '-'
        if (node.children && node.children.length > 0) {
          markLeaf(node.children as RecruitPostCascaderNode[])
          node.isLeaf = false
        } else {
          node.isLeaf = true
        }
      })
      return nodes
    }
    postOptions.value = markLeaf(tree)
  } catch (error) {
    console.warn('岗位数据加载失败', error)
  }
}

const open = async (type: 'create' | 'update' = 'create', id?: number) => {
  formType.value = type
  currentId.value = id
  visible.value = true
  resetForm()
  await loadPostOptions()

  // 如果是更新操作，需要获取现有数据
  if (type === 'update' && id) {
    try {
      loading.value = true
      const data = await RecruitInterviewApi.getRecruitInterview(id)
      formData.name = data.name || ''
      formData.post = data.post || undefined
      formData.inviter = data.inviter || undefined
      formData.interviewTime =  data.interviewTime || ''
      formData.urgentPhone = data.urgentPhone || ''
      formData.remark = data.remark || ''
    } catch (error) {
      console.error('获取面试信息失败', error)
      message.error('获取数据失败')
    } finally {
      loading.value = false
    }
  }
}

const setFormData = (data: any) => {
  formData.name = data.name || ''
  formData.post = data.post || undefined
  formData.inviter = data.inviter || undefined
  formData.interviewTime =  data.interviewTime || ''
  formData.urgentPhone = data.urgentPhone || ''
  formData.remark = data.remark || ''
}

const emit = defineEmits(['success'])

const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  loading.value = true
  try {
    const payload: RecruitInterview = {
      name: formData.name,
      post: formData.post,
      inviter: formData.inviter,
      interviewTime: formData.interviewTime,
      urgentPhone: formData.urgentPhone,
      remark: formData.remark,
      status: '0'
    }

    if (formType.value === 'create') {
      await RecruitInterviewApi.createRecruitInterview(payload)
      message.success(t('common.createSuccess'))
    } else {
      // 更新操作需要包含ID
      if (currentId.value) {
        await RecruitInterviewApi.updateRecruitInterview({
          ...payload,
          id: currentId.value
        })
        message.success(t('common.updateSuccess'))
      }
    }
    emit('success')
    visible.value = false
  } finally {
    loading.value = false
  }
}

// 暴露方法给父组件
defineExpose({ open, setFormData })
</script>
